package com.tarena.lbs.user.dao.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tarena.lbs.user.dao.mapper.UserMapper;
import com.tarena.lbs.user.dao.repository.UserRepository;
import com.tarena.lbs.user.pojo.po.UserPO;
import com.tarena.lbs.user.pojo.query.UserQuery;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.user.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

@Repository
public class UserRepositoryImpl implements UserRepository {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserPO getByPhone(String phone) {
        QueryWrapper<UserPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",phone);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public Long countUserByPhone(String phone) {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("phone",phone);
        return userMapper.selectCount(queryWrapper);
    }

    @Override
    public void save(UserPO poParam) {
        userMapper.insert(poParam);
    }

    @Override
    public UserPO getById(Integer userId) {
        return userMapper.selectById(userId);
    }

    @Override
    public Integer ifRole(Integer userId) {
        Integer role = userMapper.selectById(userId).getProviderType();
        return role;
    }


    @Override
    public void updateStatusById(int status, Integer userId) {
        UserPO userPO = new UserPO();
        userPO.setStatus(status);
        userPO.setId(userId);
        userMapper.updateById(userPO);
    }

    @Override
    public List<UserVO> pageList(UserQuery query) {
        QueryWrapper<UserPO> queryWrapper = new QueryWrapper<>();

        // 根据手机号模糊查询
        if (StringUtils.hasText(query.getPhone())) {
            queryWrapper.like("phone", query.getPhone());
        }

        // 根据昵称模糊查询
        if (StringUtils.hasText(query.getNickName())) {
            queryWrapper.like("nick_name", query.getNickName());
        }

        // 根据状态查询
        if (query.getStatus() != null) {
            queryWrapper.eq("status", query.getStatus());
        }

        // 添加排序
        queryWrapper.orderByDesc("reg_time");
        List<UserPO> userPOList = userMapper.selectList(queryWrapper);
        List<UserVO> userVOList = userPOList.stream().map(userPO -> {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(userPO, userVO);
            return userVO;
        }).collect(Collectors.toList());

        return userVOList;
    }
}